# -*- coding: utf-8 -*-
'''
Created on 2013-5-8
@author: CL.Lam
'''
from flask import session, redirect, request
from flask.helpers import url_for

from sqlalchemy.sql.expression import and_
from sys2do.model import qry, db
from sys2do.constant import LOG_TYPE_UPDATE




__all__ = ['getCurrentShopID', 'getCurrentShopProfile', 'getCurrentUserID', 'getCurrentShop',
           'checkLogin', 'getPermission', 'getAllPermission', 'getAnyPermission',
           'inGroup', 'inAllGroup', 'inAnyGroup', 'getOption', 'compareObject',
           'checkUpdate', 'makeUpdateLog', 'translateIvt', 'guessNo']


getCurrentShopID = lambda : session.get( 'currentShopID', None )

getCurrentUserID = lambda : session['user_profile']['id']

def getCurrentShop():
    from sys2do.model import Shop
    sid = getCurrentShopID()
    return Shop.get( sid )


def getCurrentShopProfile():
    from sys2do.model import qry, ShopProfile
    sid = getCurrentShopID()
    return qry( ShopProfile ).filter( and_( ShopProfile.active == 0, ShopProfile.shopID == sid ) ).one()


def checkLogin():
    if not session.get( 'login', None ):
        return redirect( url_for( 'bpAuth.login', next = request.url ) )



getPermission = lambda name : 'user_profile' in session and name in session['user_profile']['permissions']
getAllPermission = lambda names : all( map( lambda p: getPermission( p ), names ) )
getAnyPermission = lambda names : any( map( lambda p: getPermission( p ), names ) )


inGroup = lambda name : 'user_profile' in session and name in session['user_profile']['groups']
inAllGroup = lambda names:  all( map( lambda r: inGroup( r ), names ) )
inAnyGroup = lambda names:  any( map( lambda r: inGroup( r ), names ) )

'''
def getOption( clz, cds, order_by ):
    def _f():
        result = qry( clz ).filter( and_( *cds ) ).order_by( order_by )
        result = [( '', '' ), ] + [( unicode( r.id ), unicode( r ) ) for r in result]
        return result
    return _f
'''

def getOption( clz, cds, order_by ):
    result = qry( clz ).filter( and_( *cds ) ).order_by( order_by )
    result = [( '', '' ), ] + [( unicode( r.id ), unicode( r ) ) for r in result]
    return result



def compareObject( old_obj, new_obj ):
    old_keys = old_obj.keys()
    new_keys = new_obj.keys()
    result = {
              "new" : [],
              "update" : [],
              "delete" : [],
              }

    for key in list( set( old_keys ).intersection( set( new_keys ) ) ):
        old_val = old_obj[key][0]
        new_val = new_obj[key][0]

        if old_val is None : old_val = ''
        if new_val is None : new_val = ''

        old_val = unicode( old_val )
        new_val = unicode( new_val )

        if old_val != new_val:
            result['update'].append( ( old_obj[key][1], old_obj[key][0], new_obj[key][0] ) )

    for key in list( set( old_obj ).difference( set( new_obj ) ) ):
        result['delete'].append( ( old_obj[key][1], old_obj[key][0] ) )

    for key in list( set( new_obj ).difference( set( old_obj ) ) ):
        result['new'].append( ( new_obj[key][1], new_obj[key][0] ) )

    return result


def checkUpdate( oldCopy, newCopy ):
    checkLog = compareObject( oldCopy, newCopy )
    logContent = []
    for ( label, v ) in checkLog.get( 'new', [] ) : logContent.append( u"添加项目 [%s]，值为 [%s]。" % ( label, v ) )
    for ( label, v ) in checkLog.get( 'delete', [] ) : logContent.append( u"删除项目 [%s]，值为 [%s]。" % ( label, v ) )
    for ( label, oldv, newv ) in checkLog.get( 'update', [] ) : logContent.append( u"项目 [%s] 从 [%s] 变更为 [%s]。" % ( label, oldv, newv ) )
    return logContent



def makeUpdateLog( obj, oldCopy, newCopy, extLog = [] ):
    from sys2do.model import SysLog
    logContent = checkUpdate( oldCopy, newCopy )
    logContent.extend( extLog )
    if logContent:
        db.add( SysLog( refClz = obj.__class__.__name__, type = LOG_TYPE_UPDATE, refID = obj.id, remark = '\n'.join( logContent ) ) )



def translateIvt( ivt ):
    if not ivt : return ''
    if not hasattr( ivt, 'name' ) or not hasattr( ivt, 'fullPath' ) : return ''
    return {
            'IN_TRAVEL' : u'在途',
            'PURCHASE' : u'采购',
            'SOLD_OUT' : u'售出',
            'WASTAGE' : u'损耗',
            'PROCESS' : u'加工/维修',
            }.get( ivt.name, ivt.fullPath )



def guessNo( no ):
    from sys2do.model import SysDict
    prefix = no[:3]
    v = SysDict.getName( 'OBJECT_PREFIX', prefix )

    if v == 'Payterm' : return u'结算方式'
    if v == 'Paytype' : return u'支付方式'
    if v == 'InventoryLocation' : return u'仓位'
    if v == 'Supplier' : return u'供应商'
    if v == 'Customer' : return u'客户'
    if v == 'ProductType' : return u'商品类型'
    if v == 'ProductShap' : return u'商品形状'
    if v == 'ProductSeries' : return u'商品系列'
    if v == 'Shop' : return u'店铺'
    if v == 'ShopProfile' : return u'店铺配置'
    if v == 'Currency' : return u'汇率'
    if v == 'FinAccount' : return u'账户'
    if v == 'Member' : return u'会员'
    if v == 'Product' : return u'商品'
    if v == 'SO' : return u'销售'
    if v == 'PO' : return u'采购'
    if v == 'DN' : return u'调拨'
    if v == 'RGN' : return u'退货'
    if v == 'InventoryNote' : return u'出入库'
    if v == 'FinNote' : return u'进出账单'

    return None
